package operation;
import book.*;
import java.util.Scanner;

//新增图书
public class AddOperation implements Operation{
    //数组扩容
    private static Book[] copyTo(Book[] books) {
        Book[] ret = new Book[books.length*2];
        for(int i = 0; i < books.length; i++) {
            ret[i] = books[i];
        }
        return ret;
    }
    @Override
    public void work(BookShelf bookShelf) {
        //添加图书需要考虑扩容的问题，其实这里使用一个顺序表会好很多
        int size = bookShelf.getSize();
        Book[] books = bookShelf.getBookShelf();
        if(size == books.length) {
            //使用拷贝进行二倍扩容
            //此处应该可以使用Arrays.copyTo
            //逻辑：调用书架公开方法，设置暑假数组；将已扩容的数组传过去
            //设置完成之后需要重新获取数组
            bookShelf.setBooks(AddOperation.copyTo(books));
            books = bookShelf.getBookShelf();
        }

        Scanner in = new Scanner(System.in);
        System.out.println("请您输入书名：");
        String title = in.nextLine();
        System.out.println("请您输入作者名：");
        String author = in.nextLine();
        System.out.println("请您输入价格：");
        double price = in.nextDouble();

        Book book = new Book(title,author,price);
        books[size] = book;
        //有效数据增加
        bookShelf.setSize(size+1);
        System.out.println("添加成功！");
    }
}
